#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <WiFiUdp.h>
#include <WakeOnLan.h>

WiFiUDP UDP;
WakeOnLan WOL(UDP);

const char* ssid = "RedmiK30";
const char* password = "q1w2e3r4";

const char* host = "192.168.0.24"; //需要访问的域名
const int port = 8080;  // 需要访问的端口
const String url = "/computer-manager/manager/echo";   // 需要访问的地址

void setup() {
  Serial.begin(9600);
  Serial.println();
  Serial.print("connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password); // 连接WIFI
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP()); // 显示WIFI地址

  // WOL 唤醒
  Serial.println("WOL start...");
  // wakeOnLan();
}

void loop() {
  Serial.print("connecting to ");
  Serial.println(host);

  WiFiClient client;

  /**
     测试是否正常连接
  */
  if (!client.connect(host, port)) {
    Serial.println("connection failed");
    return;
  }
  delay(10);

  String postRequest = (String)("POST ") + url + "?msg=test HTTP/1.1\r\n" +
                       "Content-Type: application/json;charset=utf-8\r\n" +
                       "Host: " + host + "\r\n" +
                       "Connection: close\r\n\r\n";
  Serial.println(postRequest);
  client.print(postRequest);  // 发送HTTP请求

  /**
     展示返回的所有信息
  */
  String status_response = client.readStringUntil('\n');
  Serial.print("status_response: ");
  Serial.println(status_response);
  // 使用find跳过HTTP响应头
  if (client.find("\r\n\r\n")) {
    Serial.println("Found Header End. Start Parsing.");
  }
  parseInfo(client);
  /**
    while (line.length() != 0) {
    Serial.println(line);
    line = client.readStringUntil('\n');
    }
    Serial.println(line);
  */
  client.stop();
  delay(3000);
}

void wakeOnLan() {
  // MAC 地址
  const char *MACAddress = "00:F0:D2:D0:74:06";
  // 发送 WOL 数据包
  WOL.sendMagicPacket(MACAddress);
  Serial.println("wakeOnLan finish");
}

void parseInfo(WiFiClient client) {
  const size_t capacity = JSON_OBJECT_SIZE(1) + 3 * JSON_OBJECT_SIZE(3) + 140;
  DynamicJsonDocument doc(capacity);
  Serial.println(client);
  deserializeJson(doc, client);
  const char* name_str = doc["code"];
  const char* message_str = doc["message"];
  const char* data_str = doc["data"];

  Serial.print("name = ");
  Serial.println(name_str);
  Serial.print("message = ");
  Serial.println(message_str);
  Serial.print("data = ");
  Serial.println(data_str);
}
